package com.yeu;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }
    /** 获取真实用户IP **/
	public String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		} else {
			return request.getHeader("x-forwarded-for");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8"); 
		request.setCharacterEncoding("UTF-8");
		//request.setAttribute("info", "欢迎登录仰恩说");
		//request.getRequestDispatcher("login.jsp").forward(request, response); //此处重定向不行
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
		String userNumber = request.getParameter("userNumber");
		String password = request.getParameter("password");
		String ipAddress = getRemortIP(request);
		String mLog = null;
		System.out.println("account:" + userNumber + "\npassword:" + password + "\nipAddress:" + ipAddress); // 打印出来看一看
		System.out.println("【-- 登录帐号 --】");
		PrintWriter pw = response.getWriter();
		
		if (userNumber.equals("") || password.equals("")) {
			pw.print("用户名密码不能为空");
			pw.flush();
			return;
		}
		/* 登录模块 */
		try {
			Connection connect = DBUtil.getConnect();
			Statement statement = (Statement) connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
			ResultSet result;

			String sqlQuery = "select * from " + DBUtil.TABLE_PASSWORD + " where userNumber='" + userNumber + "'";
			// 查询类操作返回一个ResultSet集合，没有查到结果时ResultSet的长度为0
			result = statement.executeQuery(sqlQuery); // 先查询同样的账号（比如手机号）是否正确
			if (result.next() && !userNumber.equals("")) { // 已存在 result.next()
				if (result.getString("userPassword").equals(password)) {
					//登录成功！
					result.close();//在一个jdbc操作过程中不能同时执行两个操作，要先关闭一个在执行另一个
					//生成Cookie并存到数据库	
					Cookie mCookie = new Cookie("userNumber", userNumber);
					mCookie.setMaxAge(60*60*24*7);
					response.addCookie(mCookie);
					//转发
					//request.getRequestDispatcher("Index").include(request, response); //此处重定向不行
					//response.sendRedirect("Index");
					pw.print("0");
					pw.flush();
					//将日志信息插入日志表
					mLog = "登录成功";
					String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('" + userNumber + "','" + password +"','" + ipAddress + "','" + mLog + "')";
					statement.executeUpdate(sqlInsertLog); // 插入日志
				} else {
					//将日志信息插入日志表
					mLog = "密码错误";
					String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('" + userNumber + "','" + password +"','" + ipAddress + "','" + mLog + "')";
					statement.executeUpdate(sqlInsertLog); // 插入帐号密码
					
//					request.setAttribute("info", "密码错误");
//					request.getRequestDispatcher("login.jsp").forward(request, response); //此处重定向不行
					pw.println("密码错误");
					pw.flush();
					System.err.println("密码错误");
				}

			} else { // 帐号不存在
				//将日志信息插入日志表
				mLog = "帐号错误";
				String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('" + userNumber + "','" + password +"','" + ipAddress + "','" + mLog + "')";
				statement.executeUpdate(sqlInsertLog); // 插入帐号密码
				pw.println("帐号错误");
				pw.flush();
			}
			//断开数据库连接
			statement.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
	}

}
